import 'dart:io';
import 'dart:math';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_media_recorder/audio_encoder_type.dart';
import 'package:social_media_recorder/screen/social_media_recorder.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '自助默写',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '自助默写：自己录音，打乱顺序默写'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  int pre = 0;
  String afile = "";
  String storePath = "";
  int curIdx = -1;
  List<String> audioList = List.empty(growable: true);

  final AudioPlayer player = AudioPlayer();

  Future<void> saveList() async {
    var prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('audios', audioList);
  }

  Future<void> loadList() async {
    var prefs = await SharedPreferences.getInstance();
    setState(() {
      audioList = prefs.getStringList('audios') ?? audioList;
    });
  }

  void randList(List<String> list1) {
    if (list1.isEmpty) return;
    var rand1 = Random(DateTime.now().microsecond);
    for (int i = 0; i < list1.length - 1; i++) {
      var max1 = list1.length - 2 - i;
      int n = max1;
      if (max1 > 1) {
        n = rand1.nextInt(max1);
      }
      String tmp = list1[i];
      list1[i] = list1[i + n + 1];
      list1[i + n + 1] = tmp;
    }
  }

  void play(String path1) {
    FlutterIsolate.spawn(playaudio, path1);
  }

  @override
  void initState() {
    pre = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    getApplicationDocumentsDirectory().then((value) {
      setState(() {
        storePath = value.path;
      });
    });
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      loadList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            
            Row(
              children: [
                TextButton(
                  onPressed: () {
                    setState(() {
                      curIdx = -1;
                    });
                  },
                  child: const Text('清除已读标记'),
                ),
                TextButton(
                  onPressed: () {
                    randList(audioList);
                    saveList();
                    setState(() {
                      curIdx = -1;
                    });
                  },
                  child: const Text('打乱顺序'),
                ),
                TextButton(
                  onPressed: () {
                    for (int i = 0; i < audioList.length; i++) {
                      var f = File(audioList[i]);
                      if (f.existsSync()) {
                        f.deleteSync();
                      }
                    }
                    setState(() {
                      audioList = List.empty(growable: true);
                      saveList();
                    });
                  },
                  child: const Text("全部删除"),
                ),
              ],
            ),
            Expanded(
              child: SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                child: Table(
                  border: const TableBorder(
                      top: BorderSide(),
                      horizontalInside: BorderSide(),
                      bottom: BorderSide()),
                  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                  children: () {
                    var ret = List<TableRow>.empty(growable: true);
                    for (int i = 0; i < audioList.length; i++) {
                      TableRow r1 = TableRow(
                        children: [
                          Center(
                            child: Text(
                              '音频${i + 1}',
                            ),
                          ),
                          IconButton(
                            onPressed: (idx) {
                              return () {
                                play(audioList[idx]);
                                setState(() {
                                  if (curIdx < idx) {
                                    curIdx = idx;
                                  }
                                });
                              };
                            }(i),
                            icon: const Icon(Icons.play_arrow),
                          ),
                          IconButton(
                              onPressed: (idx) {
                                return () {
                                  File(audioList[idx]).delete();
                                  setState(() {
                                    audioList.removeAt(idx);
                                    saveList();
                                  });
                                };
                              }(i),
                              icon: const Icon(Icons.delete)),
                          (i <= curIdx)
                              ? const Icon(Icons.circle_rounded)
                              : const Icon(Icons.circle_outlined),
                        ],
                      );
                      ret.add(r1);
                    }
                    return ret;
                  }(),
                ),
              ),
              
            
            ),
            SocialMediaRecorder(
              storeSoundRecoringPath: storePath,
              sendRequestFunction: (soundFile, name) {
                afile = "$storePath/$pre-${_counter++}.m4a";
                var f = File(afile);
                if (f.existsSync()) {
                  f.deleteSync();
                }
                f.create().then((value) async {
                  await soundFile.rename(afile);

                  play(afile);

                  setState(() {
                    audioList.add(afile);
                    saveList();
                  });
                });
              },
              encode: AudioEncoderType.AMR_NB,
            ),
            const Text(
              '按住录音按钮录入一个词语或句子：',
            ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

@pragma('vm:entry-point')
void playaudio(String arg) {
  var player = AudioPlayer();
  player.play(UrlSource('file://$arg'));
}
